#include "StdAfx.h"
#include "UIHookWindow.h"
#include "UIWindow.h"

map<HWND, CUIWindow*> CUIHookWindow::m_WindowObjMap;
CUIHookWindow::CUIHookWindow( void )
{

}


CUIHookWindow::~CUIHookWindow( void )
{

}

BOOL CUIHookWindow::HookWindow( CUIWindow* pWnd )
{
    WNDPROC OldWndProc = ( WNDPROC )::GetWindowLong( pWnd->GetHwnd(), GWL_WNDPROC );
    pWnd->SaveOldWindowProc( OldWndProc );
    ::SetWindowLong( pWnd->GetHwnd(), GWL_WNDPROC, ( LONG )NewWindowProc );
    m_WindowObjMap.insert( pair<HWND, CUIWindow*>( pWnd->GetHwnd(), pWnd ) );
    return TRUE;
}

void CUIHookWindow::UnHookWindow( CUIWindow* pWnd )
{
    WNDPROC oldWndProc = pWnd->GetOldWindowProc();

    if ( NULL != oldWndProc )
    {
        ::SetWindowLong( pWnd->GetHwnd(), GWL_WNDPROC, ( LONG )oldWndProc );
    }

    pWnd->SaveOldWindowProc( NULL );
    m_WindowObjMap.erase( pWnd->GetHwnd() );
}

CUIWindow* CUIHookWindow::FromeHandle( HWND hWnd )
{
    map<HWND, CUIWindow*>::iterator it = m_WindowObjMap.begin();

    for ( it; it != m_WindowObjMap.end(); it++ )
    {
        if ( it->first == hWnd )
        {
            return ( CUIWindow* )( it->second );
        }
    }

    return NULL;
}

CUIFrame* CUIHookWindow::GetMainFrameWnd()
{
    map<HWND, CUIWindow*>::iterator it = m_WindowObjMap.begin();

    for ( it; it != m_WindowObjMap.end(); it++ )
    {
        CUIWindow* pWnd = it->second;
        TCHAR sClassName[MAX_PATH] = {0};
        ::GetClassName( pWnd->GetHwnd(), sClassName, MAX_PATH );

        if ( 0 == _tcscmp( sClassName, _T( "#32770" ) ) )
        {
            return ( CUIFrame* )pWnd;
        }
    }

    return NULL;
}

UINT CUIHookWindow::NewWindowProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam )
{
    CUIWindow* pWnd = FromeHandle( hWnd );

    if ( NULL != pWnd )
    {
        return pWnd->ProcessUIMsg( uMsg, wParam, lParam );
    }

    return ::DefWindowProc( hWnd, uMsg, wParam, lParam );
}
